/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.wx.statweb.action;

import static cn.ac.iie.di.wx.statweb.action.BaiduTieBaWebStatAction.logger;
import cn.ac.iie.di.wx.statweb.utils.MongoHelper;
import cn.ac.iie.di.wx.statweb.utils.PicCopy;
import cn.ac.iie.di.wx.statweb.vo.GroupDataVo;
import cn.ac.iie.di.wx.statweb.vo.WarningVo;
import com.alibaba.fastjson.JSON;
import com.mongodb.BasicDBObject;
import com.mongodb.client.MongoCursor;
import static com.opensymphony.xwork2.Action.SUCCESS;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.bson.Document;

/**
 *
 * @author Administrator
 */
public class DataTableAction {

    static Logger logger = Logger.getLogger(DataTableAction.class.getName());
    private String id;//前台获取的id
    private String _id;//mongo库字段，以下都是
    private String ct;
    private String pt;
    private String it;
    private String ut;
    private String gettime;
    private String title;
    private String cont;
    private String nrd;
    private String wx_nap;
    private String wx_nad;
    private String url;
    private String abstr;
    private String nsnd;
    private String wx_sfrom;
    private String wx_au;
    private String[] wx_lfn;
    private String tableName;

    public String selectTable() {
        HttpServletRequest request = ServletActionContext.getRequest();
        tableName = request.getParameter("tableName");
        return "success";
    }

    public String getDataTableList() {
        PrintWriter pw = null;
        try {

            //获取分页信息
            HttpServletRequest req = ServletActionContext.getRequest();
            req.setCharacterEncoding("UTF-8");
            String selectTable = req.getParameter("tableName");
            String queryid = req.getParameter("queryid");//有值
            String starttime = req.getParameter("starttime");//无值
            String endtime = req.getParameter("endtime");//无值
            String start = req.getParameter("start");//游标的起点，从0，0×limit顺序排序，取值为limit×start-limit*（start+1）
            String limit = req.getParameter("limit");//步长25
            String[] hosts = new String[1];
            hosts[0] = "10.136.140.86:23456";//可以存配置文件
            MongoHelper mongoHelper = new MongoHelper(hosts, "wx_msgs1", selectTable, "w123", "w123");
            String keyCol = "_id";//索引
            String retField = "_id;ct;pt;it;ut;title;nrd;wx_nap;wx_nad";//列名集合
            String[] retFields = retField.split(";");//可以存配置文件

            logger.info("selectTable = "+selectTable+",queryid = " + queryid + ",starttime = " + starttime + ",endtime = " + endtime);
            logger.info("游标起点：" + start + ",一共" + limit + "条");
            HttpServletResponse response = ServletActionContext.getResponse();
            response.reset();
            response.setContentType("text/html;charset=utf-8");
            response.setCharacterEncoding("UTF-8");
            pw = response.getWriter();
            List<HashMap<String, Object>> allList = new ArrayList<>();
            //按照分页信息查询mongo,条件查询和默认都走这个接口，
            //条件查询的时候按是否有条件进行mongo的接口区分
            //只有ID的时候走queryByID
            long allcount = mongoHelper.collection.count();
            if (queryid != null) {
                logger.info("query by id");
                Collection<String> keyss = new ArrayList<>();
                keyss.add(queryid);
                allList = mongoHelper.queryByID("_id", keyss, retFields);
                //两者都包含的时候走queryByID，同时对时间范围进行判断
                if (starttime != null && endtime != null) {
                    for (HashMap<String, Object> queryIdList1 : allList) {
                        String it = (String) queryIdList1.get("it");
                        long ittime = Long.parseLong(it);
                        Date itdate = new Date(ittime);
                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Date startdate = format.parse(starttime);
                        Date enddate = format.parse(endtime);
                        if (startdate.before(itdate) && enddate.after(itdate)) {
                            logger.info("在时间范围内");//在时间范围内的进行显示，否则返回一个没有数据的json
                        }
                    }
                }
            } else if (starttime != null && endtime != null) {
                //判断开始时间是否小于等于结束时间//只有时间范围的时候走queryBySelection
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                String time = "1970-01-06 11:45:55";
                Date startdate = format.parse(starttime);
                Date enddate = format.parse(endtime);
                if (startdate.before(enddate) || startdate.getTime() == enddate.getTime()) {
                    logger.info("开始时间小于或者等于结束时间");
                    BasicDBObject basicDBObject = new BasicDBObject();
                    basicDBObject.put("it", new BasicDBObject().append("$gte", Long.parseLong("1500627025")));
                    basicDBObject.put("it", new BasicDBObject().append("$lte", Long.parseLong("1500627025")));
                    int startint = 0;
                    allList = mongoHelper.queryBySelection(basicDBObject, retFields, startint, Integer.parseInt(limit));
                }
            } else {

                logger.info("所有的条数============" + allcount);
                allList = mongoHelper.listAll(keyCol, retFields, Integer.parseInt(start), Integer.parseInt(limit));
            }

            //游标和步长是从前台传递的
            List<GroupDataVo> list = new ArrayList<GroupDataVo>(Integer.parseInt(limit));
            for (int i = 0; i < Integer.parseInt(limit); i++) {
                HashMap<String, Object> map = allList.get(i);
                list.add(new GroupDataVo(
                        map.get("_id").toString(),
                        map.get("ct").toString(),
                        map.get("pt").toString(),
                        map.get("it").toString(),
                        map.get("ut").toString(),
                        map.get("title").toString(),
                        map.get("nrd").toString(),
                        map.get("wx_nap").toString(),
                        map.get("wx_nad").toString()));
            }
            Object toJSON = JSON.toJSON(list);
            String toJSONstr = " {\"totalProperty\":\"" + allcount + "\",\"root\":" + toJSON.toString() + "}";
            pw.print(toJSONstr);
            //将mongo数据封装到DataVo类中、
            //封装到前台映射json中
            return SUCCESS;
        } catch (IOException ex) {
            logger.error("IOerror" + ex.getMessage(), ex);
            return SUCCESS;
        } catch (Exception ex) {
            logger.error("其他错误" + ex.getMessage(), ex);
            return SUCCESS;
        } finally {
            pw.close();
        }

    }

    public String checkLog() {
        try {
            HttpServletRequest request = ServletActionContext.getRequest();
            HttpServletResponse response = ServletActionContext.getResponse();
            response.reset();
            response.setContentType("text/html;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            id = request.getParameter("id");
            String selectTable = request.getParameter("tableName");
            String[] hosts = new String[1];
            hosts[0] = "10.136.140.86:23456";//可以存配置文件
            MongoHelper mongoHelper = new MongoHelper(hosts, "wx_msgs1", selectTable, "w123", "w123");
            String retField = "_id;ct;pt;it;ut;gt;title;cont;nrd;wx_nap;wx_nad;url;abstr;nsnd;wx_sfrom;wx_au;wx_lfn;";//需要提取的列名集合
            String[] retFields = retField.split(";");//可以存配置文件
            Collection<String> keys = new ArrayList<>(1);
            keys.add(id);
            List<HashMap<String, Object>> list = mongoHelper.find("_id", keys, retFields);
//            List<HashMap<String, Object>> list =new ArrayList<>();
//            HashMap<String, Object> map = new HashMap<String, Object>();
//            for (int i = 0; i < retFields.length; i++) {
//                map.put(retFields[i], retFields[i]);
//            }
//            list.add(map);
            logger.info("获取ID" + id + ",获取结果集大小 " + list.size());
            for (HashMap<String, Object> list1 : list) {
                for (String reField : retFields) {
                    logger.info("key = " + reField + ", value = " + list1.get(reField));
                    //设置字段接收值，用于传往前台进行显示
                    //图片类型先进行查找然后写入
                    //set get 方法没有，数据类型需要确定
                    if (reField.equals("_id")) {
                        id = String.valueOf(list1.get(reField));
                    }
                    if (reField.equals("ct")) {
                        ct = String.valueOf(list1.get(reField));
                    }
                    if (reField.equals("pt")) {
                        pt = String.valueOf(list1.get(reField));
                    }
                    if (reField.equals("it")) {
                        it = String.valueOf(list1.get(reField));
                    }
                    if (reField.equals("ut")) {
                        ut = String.valueOf(list1.get(reField));
                    }
                    if (reField.equals("gt")) {
                        gettime = String.valueOf(list1.get(reField));
                    }
                    if (reField.equals("title")) {
                        title = String.valueOf(list1.get(reField));
                    }
                    if (reField.equals("cont")) {
                        cont = String.valueOf(list1.get(reField));
                    }
                    if (reField.equals("nrd")) {
                        nrd = String.valueOf(list1.get(reField));
                    }
                    if (reField.equals("wx_nap")) {
                        wx_nap = String.valueOf(list1.get(reField));
                    }
                    if (reField.equals("wx_nad")) {
                        wx_nad = String.valueOf(list1.get(reField));
                    }
                    if (reField.equals("url")) {
                        url = String.valueOf(list1.get(reField));
                    }
                    if (reField.equals("abstr")) {
                        abstr = (String) list1.get(reField);//无摘要的情况写无
                    }
                    if (reField.equals("nsnd")) {
                        nsnd = String.valueOf(list1.get(reField));
                    }
                    if (reField.equals("wx_sfrom")) {
                        wx_sfrom = (String) list1.get(reField);
                    }
                    if (reField.equals("wx_au")) {
                        wx_au = "";
                        ArrayList<Object> wx_au_arr = (ArrayList) list1.get(reField);
                        logger.info("wx_au的内容，长度" + wx_au_arr.size());
                        for (int i = 0; i < wx_au_arr.size(); i++) {
                            logger.info("第" + i + "个内容" + wx_au_arr.get(i));
                            if (wx_au_arr.get(i) != null) {
                                wx_au += wx_au_arr.get(i);
                                if (i < wx_au_arr.size() - 1) {
                                    wx_au += ";";
                                }
                            }
                        }
                    }
                    if (reField.equals("wx_lfn")) {

                        ArrayList<Object> wx_au_arr = (ArrayList) list1.get(reField);
                        //不能转化成字符串数组，会报转换异常错误
                        wx_lfn = new String[wx_au_arr.size()];
//                        String wxdataPath = "/home/ycl/plot/new/plot_test/pic/ssyq_sougou/";
////                        String wxdataPath=PicCopy.readProperties("wxdataPath");
//                        File file = new File(wxdataPath);
//                        if (!file.isDirectory()) {
////                            file.mkdirs();//目录不存在
//                            logger.info("路径不存在");
//                        } else {
//                            String[] filelist = file.list();//相对路径
//
//                        }
                        //文件复制到当前项目文件夹下，先清空原有图片，
                        String wxdataWebPath = PicCopy.readProperties("wxdataWebPath");
                        File webfile = new File(wxdataWebPath);
                        if (webfile.isDirectory()) {
                            File[] webfilelist = webfile.listFiles();//相对路径
                            logger.info(wxdataWebPath + "共" + webfilelist.length + "个文件");
                            for (int j = 0; j < webfilelist.length; j++) {
                                //清除原有图片
                                boolean flag = webfilelist[j].delete();
                                logger.info(j + "删除结果" + flag);
                            }
                        } else {
                            logger.info("路径不存在，创建结果" + webfile.mkdirs());
                        }
                        for (int i = 0; i < wx_au_arr.size(); i++) {
                            if (wx_au_arr.get(i) != null) {
//                                wx_lfn += wx_au_arr.get(i);
//                                String abpath=(String) wx_au_arr.get(i);//实际图片路径
                                String abpath = "/home/ycl/"+(i+1)+"_pic.png";//测试用的图片存储路径
                                File remoteFile = new File(abpath);
                                if (remoteFile.isFile() && remoteFile.canRead()) {
                                    logger.info("文件存在" + abpath);
                                } else {
                                    logger.warn("文件不存在" + abpath);
                                }
                                int filelastnameindex = abpath.lastIndexOf("/");
                                String filelastname = abpath.substring(filelastnameindex + 1);
                                logger.info("获取相对文件名" + filelastname);

                                //复制新文件
                                File f = new File(wxdataWebPath + filelastname);
                                logger.info("复制到项目中" + wxdataWebPath + filelastname);
                                wx_lfn[i] = PicCopy.readProperties("wxdataWebabstrPath") + filelastname;
                                if (f.exists()) {
                                    PicCopy.copyFile(new File(abpath), f);
                                } else {
                                    try {
                                        f.createNewFile();
                                        PicCopy.copyFile(new File(abpath), f);
                                    } catch (IOException ex) {
                                        logger.error(ex.getMessage(), ex);
                                    }
                                }
//                                if (i < wx_au_arr.size() - 1) {
//                                    wx_lfn += ";";
//                                }
                            }
                        }
//应为字符串数组，用于提取图片
                    }
                }
            }

            return SUCCESS;
        } catch (Exception ex) {
            logger.error("其他错误" + ex.getMessage(), ex);
            return SUCCESS;
        }
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String get_Id() {
        return _id;
    }

    public void set_Id(String _id) {
        this._id = _id;
    }

    public String getCt() {
        return ct;
    }

    public void setCt(String ct) {
        this.ct = ct;
    }

    public String getPt() {
        return pt;
    }

    public void setPt(String pt) {
        this.pt = pt;
    }

    public String getIt() {
        return it;
    }

    public void setIt(String it) {
        this.it = it;
    }

    public String getUt() {
        return ut;
    }

    public void setUt(String ut) {
        this.ut = ut;
    }

    public String getGettime() {
        return gettime;
    }

    public void setGettime(String gettime) {
        this.gettime = gettime;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getCont() {
        return cont;
    }

    public void setCont(String cont) {
        this.cont = cont;
    }

    public String getNrd() {
        return nrd;
    }

    public void setNrd(String nrd) {
        this.nrd = nrd;
    }

    public String getWx_nap() {
        return wx_nap;
    }

    public void setWx_nap(String wx_nap) {
        this.wx_nap = wx_nap;
    }

    public String getWx_nad() {
        return wx_nad;
    }

    public void setWx_nad(String wx_nad) {
        this.wx_nad = wx_nad;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getAbstr() {
        return abstr;
    }

    public void setAbstr(String abstr) {
        this.abstr = abstr;
    }

    public String getNsnd() {
        return nsnd;
    }

    public void setNsnd(String nsnd) {
        this.nsnd = nsnd;
    }

    public String getWx_sfrom() {
        return wx_sfrom;
    }

    public void setWx_sfrom(String wx_sfrom) {
        this.wx_sfrom = wx_sfrom;
    }

    public String getWx_au() {
        return wx_au;
    }

    public void setWx_au(String wx_au) {
        this.wx_au = wx_au;
    }

    public String[] getWx_lfn() {
        return wx_lfn;
    }

    public void setWx_lfn(String[] wx_lfn) {
        this.wx_lfn = wx_lfn;
    }

    public String getTableName() {
        return tableName;
    }

    public void setTableName(String tableName) {
        this.tableName = tableName;
    }

}
